<?php

namespace App\Http\Controllers\backend;

use App\Model\Backend\ItemModel;
use App\Model\Backend\ItemTasksAccessoryModel;
use App\Model\Backend\ItemTasksModel;
use App\Model\Backend\TaskLogModel;
use App\Model\Backend\QiyehaoModel;
use Illuminate\Http\Request;

use App\Model\Backend\Member;


use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;


use App\Model\Backend\CreditModel;
use App\Model\Backend\PerformanceAreaModel;
use App\Model\Backend\PerformanceRatioModel;

use App\Http\Requests;


use App\Model\Backend\Expense;

use App\Model\Backend\ExpenseType;
use Illuminate\Support\Facades\Input;
use TomLingham\Searchy\Facades\Searchy;
use App\Model\Backend\MessageModel;
use Chumper\Zipper\Zipper;

class WorkController extends Controller
{

    //所有工作台信息
    public function index()
    {

        $uid = session('member')['uid'];
        $task = new ItemTasksModel();
        $tasks = $task->showTasks($uid);
        $shan = DB::table('member_role')->where(['uid' => $uid, 'rid' => 23])->first();

        if ($shan) {
            $items = ItemModel::where(['member_id' => $uid])->get();
            foreach ($items as $o => $p) {
                $taskAll[] = $task->Where(['item_id' => $p['id'], 'task_status' => 21])->orWhere(['item_id' => $p['id'], 'task_status' => 22])->orderBy('id', 'ASC')->get();
            }
            $val = array();
            foreach ($taskAll as $k => $v) {
                foreach ($v as $a => $b) {
                    $val[] = $b;
                }
            }
            $item = new ItemModel();
            $member = new Member();
            $arr = array();
            foreach ($val as $k => $v) {
                $itemInfo = $item->select(['item_name', 'member_id'])->find($v['item_id']);
                $n = $member->find($itemInfo['member_id']);
                $re = $task->where(['item_id' => $v['item_id']])->get();
                foreach ($re as $i => $y) {
                    if ($y['id'] == $v['id']) {
                        $arr[$v['item_id']]['common'][$i] = $y;
                    }
                }
                $arr[$v['item_id']]['item_name'] = $itemInfo['item_name'];
                $arr[$v['item_id']]['username'] = $n['username'];
                $arr[$v['item_id']]['item_id'] = $v['item_id'];

            }
            ksort($arr);
            $checks = $arr;
        } else {
            $checks = $task->showCheck($uid);
        }

        //dd($tasks);

        $join_item_name = $this->get_item_name_expense();

        //未分配任务项目
        $i_names=[];
        if($uid==9){
            $i_names=  ItemModel::where(['item_status'=>0])->where('created_at','>','2016-09-18 09:43:46')->get();
        }
        return view('backend.work.index', ['tasks' => $tasks, 'checks' => $checks, 'join_item_name' => $join_item_name,'i_names'=>$i_names]);

    }





    //发起审核
    public function check(){

        $member_id=session('member')['uid'];
        $item_id=$_POST['item_id'];
        $id=$_POST['id'];
        $comment=$_POST['comment'];

        //多图片
        //explode,根据逗号拆分,trim,去除文件前后的逗号
        $files=explode(',',trim($_POST['files'],','));


        $item_name=ItemModel::find($item_id)['item_name'];
        $task_name=ItemTasksModel::find($id)['task_name'];
       // $dir="uploads/".$item_id."/".$id;
        $dir="uploads/".$item_name."/".$task_name;
        $dir=iconv('utf-8', 'gbk',$dir);
        $path="";

        //创建文件夹
       if(!file_exists($dir)){
           @mkdir($dir,0777,true);
        }
        //echo 123;die;
        //遍历每个文件
        foreach($files as $k=>$v){

            $file=str_replace('\\','/',$v);
            $file_name=substr($file,strpos($file,"/")+1);
            if(file_exists(iconv('utf-8', 'gbk',$file))){
                @rename(iconv('utf-8', 'gbk',$file),$dir."/".iconv('utf-8', 'gbk',"(待审核)".$file_name));
                $path .="(待审核)".substr($file,strpos($file,"/")+1).",";
            }else{
                return;
            }

        }

        //项目任务
        $task=new ItemTasksModel();
        $taskInfo=$task->find($id);
        $taskInfo->task_status=20;
        $res=$taskInfo->save();


        //项目附件
        $accessory=new ItemTasksAccessoryModel();
        $accessory->item_id=$item_id;
        $accessory->item_task_id=$id;
        $accessory->author=session('member')['username'];
        $accessory->path=$path;
        $accessory->comment=$comment;


        //任务日志
        $log=new TaskLogModel();
        $count=$log->where(['member_id'=>$member_id,'item_task_id'=>$id])->count();
        if($count){
           $c=$count+1;
        }else{
           $c=1;
        }

        $log->member_id=$member_id;
        $log->item_task_id=$id;
        $log->action="第".$c."次提交成果";
        $log->comment=$comment;
        if($taskInfo['task_starttime']+$taskInfo['task_deadline']*3600-time()>0){
            $log->is_overtime=0;
        }else{
            $log->is_overtime=1;
        }
        $log->save();

        $message=new MessageModel();
        $img= Member::find($member_id)['img'];//图片url
        $task_name=ItemTasksModel::find($id)['task_name'];//任务名
        $deadline=ItemTasksModel::find($id)['task_deadline'];//截止时间
        $task_id=ItemTasksModel::find($id)['task_id'];//任务id
        $item_id=ItemTasksModel::find($id)['item_id'];//项目ID
        $items_name=ItemModel::find($item_id)['item_name'];//项目名字

        $message->uid=$member_id;
        $message->img=$img;
        $message->deadline=strtotime($deadline);
        $message->task_id= $task_id;
        $message->task_name=$task_name;
        $message->items_id=$item_id;
        $message->items_name=$items_name;
        $message->created_at=time();
        $message->content=$items_name."-".$task_name."第".$c."次提交成果";
        $message->action="第".$c."次提交成果";
        $message->save();



        $qiyehao=new QiyehaoModel();
        //审核ID
        $userID=Member::find($taskInfo['member_id_check'])['wechat'];
        $content= ItemModel::find($item_id)['item_name']."(".ItemTasksModel::find($id)['task_name'].")——请尽快审核！";
        $qiyehao->text($userID,$content);

        if($accessory->save()&&$res&&$path){
            echo 1;

        }else{
            echo 0;
        }
    }


    public function download(request $req,$id){

        $id_all = ItemTasksAccessoryModel::where(['item_id' => $id])->get();

        $itemsInfo = ItemModel::find($id);

        $arr = array();

        foreach ($id_all as $k => $v) {
            
            if ($v['status'] == 0) {


                $task_name = ItemTasksModel::find($v->item_task_id)['task_name'];
               
                $arr[0]["$task_name"] = $v;
                

            } elseif ($v['status'] == 1) {

                $task_name = ItemTasksModel::find($v->item_task_id)['task_name'];

                
                 $arr[1]["$task_name"] = $v;

            }
        }
        return view('backend.items.filedownload', compact('arr', 'itemsInfo'));
    }



    public function uploads($id,$tid,$file,$fname='uploads'){

       

        $file = trim($file,',');

        $filename = substr(strrchr($file,"."),1);

        $img = trim($file,',');
        if($fname=='uploads'){
            $item_name=ItemModel::find($id)['item_name'];
            $task_name=ItemTasksModel::find($tid)['task_name'];

            $url = public_path()."/$fname/$item_name/$task_name/$file";
            $url = iconv('utf-8', 'gbk',$url);
              
        }elseif($fname=='uploadsExpense'){
            $url = public_path()."/$fname/$id/$tid/$file";
            $url = iconv('utf-8', 'gbk',$url);

                        
        }

        //$url = iconv('gbk', 'utf-8',$url);

        //return response()->download($url);

        //设置文件类型
        if( $filename=='jpg'||$filename=='jpeg' ){
            $type = 'image/jpg';
        }elseif( $filename=='png' ){
            $type = 'image/png';
        }elseif( $filename=='doc' ){
            $type = 'application/msword';
        }elseif( $filename=='xls' ){
            $type = 'application/vnd.ms-excel';
        }elseif( $filename=='rar' ){
            $type = 'application/octet-stream';
        }elseif( $filename=='txt' ){
            $type = 'text/plain';
        }elseif( $filename=='zip' ){
            $type = 'application/zip';
        }elseif( $filename=='wav' ){
            $type = 'audio/x-wav';
        }elseif( $filename=='mp4' ){
            $type = 'video/mpeg4';
        }elseif( $filename=='mp3' ){
            $type = 'audio/mp3';
        }elseif( $filename=='dwg' ){
            $type = 'application/x-dwg';
        }else{
            $type = 'application/zip';
        }



        header("Content-type: $type"); //设置要下载的文件类型
        header("Content-Disposition: attachment; filename=$img"); //设置要下载文件的文件名
        @readfile($url);
        exit;

    }

//审核
    public function audit(){
        $member_id=session('member')['uid'];
        $task=new ItemTasksModel();

        $taskInfo=$task->find($_POST['id']);
        $itemName=ItemModel::find($taskInfo['item_id'])['item_name'];
        $userID=Member::find($taskInfo['member_id_task'])['wechat'];
        $log=new TaskLogModel();
        $accessory=new ItemTasksAccessoryModel();

        $qiyehao=new QiyehaoModel();
        $dir="uploads/".$itemName."/".$taskInfo['task_name']."/";
        if($taskInfo['task_status']==20){
            $fujian= $accessory->where(['item_task_id'=>$_POST['id'],'status'=>0])->first();
        }elseif($taskInfo['task_status']>20){
            $fujian1= $accessory->where(['item_task_id'=>$_POST['id'],'status'=>1])->first();
        }

        if($taskInfo['task_status']==21){
            $key="商务";
        }elseif($taskInfo['task_status']==22){
            $key="客户";
        }elseif($taskInfo['task_status']==20){
            $key="专家";
        }
        //通过
        if($_POST['action']=="yes"){

            if(!empty($fujian)){
                foreach(array_filter(explode(',',$fujian['path'])) as $k=>$v){
                    @rename(iconv('utf-8', 'gbk',$dir.$v),iconv('utf-8', 'gbk',$dir."(已通过)".substr($v,strpos($v,')')+1)));
                }
                $accessory->where(['item_id'=>$taskInfo['item_id'],'item_task_id'=>$taskInfo['id'],'status'=>0])->update(['status'=>1,'path'=>str_replace('(待审核)','(已通过)',$fujian['path'])]);
            }


            $log->item_task_id=$_POST['id'];
            $log->member_id=$member_id;
            $log->action="通过".$key."审核";

           if(strtotime($taskInfo['updated_at'])+6*3600-time()>0){
                $log->is_overtime=0;
            }else{
                $log->is_overtime=1;
            }

            //message站内信
            $message=new MessageModel();
            $img= Member::find($member_id)['img'];//图片url
            $task_name=ItemTasksModel::find($_POST['id'])['task_name'];//任务名
            $deadline=ItemTasksModel::find($_POST['id'])['task_deadline'];//截止时间
            $task_id=ItemTasksModel::find($_POST['id'])['task_id'];//任务id
            $item_id=ItemTasksModel::find($_POST['id'])['item_id'];//项目ID
            $items_name=ItemModel::find($item_id)['item_name'];//项目名字

            $time=strtotime($deadline)-time();

            if ($time>0){
                $message->action="在规定时间内，通过审核";
                $message->content=$items_name."-".$task_name."在规定时间内，通过审核";
            }else{
                $message->action="超过规定时间，通过审核";
                $message->content=$items_name."-".$task_name."超过规定时间，通过审核";
            }
            $message->uid=$member_id;
            $message->img=$img;
            $message->deadline=strtotime($deadline);
            $message->task_id= $task_id;
            $message->task_name=$task_name;
            $message->items_id=$item_id;
            $message->items_name=$items_name;
            $message->created_at=time();
            $message->save();

            $comment="【感谢您的卓越成果，".$itemName."  ".$taskInfo['task_name']." 已通过".$key."审核。】";


            $tatus=$taskInfo['task_starttime']+$taskInfo['task_deadline']*3600-time();
            $shen=strtotime($taskInfo['updated_at'])+6*3600-time();
            if($taskInfo['task_status']==20&&$taskInfo['audit_rank']==0||$taskInfo['task_status']==21&&$taskInfo['audit_rank']==1||$taskInfo['task_status']==22){
                if($tatus>0&&$shen>0){
                    $taskInfo->task_status=30;
                }else{
                    $taskInfo->task_status=31;
                }
            }elseif($taskInfo['task_status']==20&&$taskInfo['audit_rank']>=1){
                $taskInfo->task_status=21;
                $shanID=ItemModel::find($taskInfo['item_id'])['member_id'];
                $weixin=Member::find($shanID)['wechat'];
                $neirong="【".$itemName."  ".$taskInfo['task_name']." 已通过专家审核,需要您的审核！】";
                $qiyehao->text($weixin,$neirong);
            }elseif($taskInfo['task_status']==21&&$taskInfo['audit_rank']==2){
                $taskInfo->task_status=22;
                $shanID=ItemModel::find($taskInfo['item_id'])['member_id'];
                $weixin=Member::find($shanID)['wechat'];
                $neirong="【".$itemName."  ".$taskInfo['task_name']." 已通过商务审核,需要您的审核！】";
                 $qiyehao->text($weixin,$neirong);
            }
            $taskInfo->save();

            //改变项目阶段
            $s=$task->where(['item_id'=>$taskInfo['item_id'],'stage_id'=>$taskInfo['stage_id']])->get();

            $biao=true;
            foreach($s as $k=>$v){
                if($v['task_status']<30&&$v['task_status']>=0){
                    $biao=false;
                    break;
                }
            }
            if($biao){
                $item=ItemModel::find($taskInfo['item_id']);
                $item->item_stage=$item['item_stage']+1;
                $item->save();
            }
            //end
            //改变项目状态
            $z=$task->where(['item_id'=>$taskInfo['item_id']])->get();
            $ji=true;
            foreach($z as $k=>$v){
                if($v['task_status']<30&&$v['task_status']>=0){
                    $ji=false;
                    break;
                }
            }
            if($ji){
                $item1=ItemModel::find($taskInfo['item_id']);
                $item1->item_status=$item1['item_status']+1;
                $item1->save();
            }
            //end




            //通知下个任务
            $tag=true;
            $level=$task->where(['item_id'=>$taskInfo['item_id']])->where('task_level','like',mb_substr($taskInfo['task_level'],0,1).'%')->get();


			// edit by tony 20160830
			// 任务表添加money(积分)字段保存
			// 插入积分,面积，效绩到credit表
			$area = ItemModel::find($taskInfo['item_id'])['area'];
			$area2 = PerformanceAreaModel::where('area_start','<=', $area)->where('area_end', '>', $area)->first();
			if(empty($area2)){
				$area2 = PerformanceAreaModel::orderBy('area_end', 'desc')->first();
			}

			$dataP = [
				'area_id' => $area2['area_id'],
				'task_id' => $taskInfo['task_id']
			];

			$percent = PerformanceRatioModel::where($dataP)->first();

			$percent = empty($percent) ? 0:$percent['percent'];
			$credit = $percent * $area;

			$credits = new CreditModel;
			$credits->taskid = $taskInfo->id;
			$credits->area = $area;
			$credits->percent = $percent;
			$credits->credit = $credit;
			$credits->save();

			$taskInfo->money = $credit;
			// End edit


            foreach($level as $k=>$v){
                if($v['task_status']<30){
                    $tag=false;
                    break;
                }
            }
            if($tag){
                $task->nextMessage($taskInfo["item_id"],$taskInfo['task_level']);

            }elseif($taskInfo['task_name']=="CAD"&&$taskInfo['audit_rank']==0||$taskInfo['task_status']==21&&$taskInfo['audit_rank']==1||$taskInfo['task_status']==22){
                $r=$task->where(['item_id'=>$taskInfo["item_id"]])->where('task_level','like',$taskInfo["task_level"].'-%')->orderBy('task_level','ASC')->get();
                $userID_a="";


                foreach($r as $k=>$v){
                    $userID_a .=Member::find($v['member_id_task'])['wechat']."|";
                    $log1=new TaskLogModel();
                    $j=$task->find($v['id']);
                    $j->task_status=10;
                    $j->task_starttime=time();
                    $j->save();
                    $log1->item_task_id=$v['id'];
                    $log1->action="任务开始";
                    $log1->save();



                    //message 表的添加
                    $message=new MessageModel();
                    $img= Member::find($member_id)['img'];//图片url
                    $task_name=ItemTasksModel::find($_POST['id'])['task_name'];//任务名
                    $deadline=ItemTasksModel::find($_POST['id'])['task_deadline'];//截止时间
                    $task_id=ItemTasksModel::find($_POST['id'])['task_id'];//任务id
                    $item_id=ItemTasksModel::find($_POST['id'])['item_id'];//项目ID
                    $items_name=ItemModel::find($item_id)['item_name'];//项目名字

                    $message->uid=$member_id;
                    $message->img=$img;
                    $message->deadline=strtotime($deadline);
                    $message->task_id= $task_id;
                    $message->task_name=$task_name;
                    $message->items_id=$item_id;
                    $message->items_name=$items_name;
                    $message->created_at=time();
                    $message->action="任务开始";
                    $message->content=$items_name."-".$task_name."任务开始";
                    $message->save();
                }
                $content_a="【".ItemModel::find($taskInfo["item_id"])['item_name']."  需要您的协助，请至工作台查看。】";
                $qiyehao->text(trim($userID_a,'|'),$content_a);
            }



            //不通过
        }elseif($_POST['action']=="no"){

            $info=$_POST['info'];
            $log->item_task_id=$_POST['id'];
            $log->member_id=$member_id;
            $log->action=$key."驳回";

            $log->comment=$info;


            //站内信message
            $message=new MessageModel();
            $img= Member::find($member_id)['img'];//图片url
            $task_name=ItemTasksModel::find($_POST['id'])['task_name'];//任务名
            $deadline=ItemTasksModel::find($_POST['id'])['task_deadline'];//截止时间
            $task_id=ItemTasksModel::find($_POST['id'])['task_id'];//任务id
            $item_id=ItemTasksModel::find($_POST['id'])['item_id'];//项目ID
            $items_name=ItemModel::find($item_id)['item_name'];//项目名字

            $message->uid=$member_id;
            $message->img=$img;
            $message->deadline=strtotime($deadline);
            $message->task_id= $task_id;
            $message->task_name=$task_name;
            $message->items_id=$item_id;
            $message->items_name=$items_name;
            $message->created_at=time();
            $message->action="专家驳回";
            $message->content=$items_name."-".$task_name."已被专家驳回";
            $message->save();
            if(strtotime($taskInfo['updated_at'])+3600-time()>0){
                $log->is_overtime=0;
            }else{
                $log->is_overtime=1;
            }
            if(!empty($fujian)){
                foreach(array_filter(explode(',',$fujian['path'])) as $k=>$v){
                    @rename(iconv('utf-8', 'gbk',$dir.$v),iconv('utf-8', 'gbk',$dir."(已驳回)".substr($v,strpos($v,')')+1)));
                }
            }else{
                foreach(array_filter(explode(',',$fujian1['path'])) as $k=>$v){
                    @rename(iconv('utf-8', 'gbk',$dir.$v),iconv('utf-8', 'gbk',$dir."(已驳回)".substr($v,strpos($v,')')+1)));
                }
            }
            if($taskInfo['task_status']==20){
                $accessory->where(['item_id'=>$taskInfo['item_id'],'item_task_id'=>$taskInfo['id'],'status'=>0])->update(['status'=>'-1','path'=>str_replace('(待审核)','(已驳回)',$fujian['path'])]);

            }elseif($taskInfo['task_status']>=21){
                $accessory->where(['item_id'=>$taskInfo['item_id'],'item_task_id'=>$taskInfo['id'],'status'=>1])->update(['status'=>'-1','path'=>str_replace('(已通过)','(已驳回)',$fujian1['path'])]);

            }
            $comment="【".$itemName."   ".$taskInfo['task_name']." 亟待调整，请至工作台查看。】(附：".$info.")";
            $taskInfo->task_status=10;
            $taskInfo->save();

            }

        //微信推送消息
        $qiyehao->text($userID,$comment);
        if($log->save()){
            echo 1;
        }else{
            echo 0;
        }


    }








//上传财务

    public function expense(Request $request){

    //dd($request);
    //拿到文件
    $file = $request->files;


    $did = $request->get('did')[0];

    if($did==0){
            
            return back()->withErrors(['messageOfStatus'=>'请选择项目!']);
            
        }




    //用户id
        $member_id=session('member')['uid'];
        $username = Member::find($member_id)->username;
        $username = iconv('utf-8', 'gbk',$username);

    //项目id
        if( $did == -1 ){
            $item_name = iconv('utf-8', 'gbk','无关联项目');
        }else{
            $item_name = ItemModel::find($did)->item_name;
            $item_name = iconv('utf-8', 'gbk',$item_name);
        }






    //拿到类型id
        $type = $request->get('type');

        foreach( $type as $k=>$v ){
        //报销类型名    
            $type_name = ExpenseType::find($v)->expense_type;
            $type_name = iconv('utf-8', 'gbk',$type_name);

            //目标路径
            $destinationPath[] = "uploadsExpense/".$username."/".$item_name."/".$type_name;

            }


        //创建目录
        foreach ($destinationPath as $v) {
                
                if(!file_exists($v)){
                    mkdir($v,0777,true);
                   
                }
                    
            }


        //定义路径的初始下标
        $move = 0;


        //循环文件
        foreach( $file as $k=>$v ){

        //文件名字符串重置
        $da = '';

            //第二层
            foreach($v as $o=>$p){

                //拼接文件名
                $da .=$p->getClientOriginalName().',';
                //移动文件
                $p->move($destinationPath[$move],iconv('UTF-8', 'GB2312', $p->getClientOriginalName()));//转编码    

               }

       //下表加一
        $move++;
        //路径变成数组,可以存入数据库
        $path[] = $da;

        }



       //默认状态
        $status = 2;
        
        //时间,金额,描述
        $salary = $request->get('salary');
        $time = $request->get('time');
        $description = $request->get('description');

        //根据类型存入数据库
        foreach( $type as $u=>$v ){


            $expense = new Expense;
    //项目id
        if( $did == -1 ){
            $name = '无关联项目';
            $item_name = $name;
        }else{
            $item_name = ItemModel::find($did)->item_name;
        }
            
            $username = Member::find($member_id)->username;
            $expense_type = ExpenseType::find($v)->expense_type;

                $arr = [

                    'type'=>$v,
                    'salary'=>$salary[$u],
                    'time'=>strtotime($time[$u]),
                    'description'=>$description[$u],
                    'status'=>$status,
                    'did'=>$did,                    
                    'uid'=>$member_id,
                    'path'=>$path[$u],
                    'username'=>$username,
                    'itemname'=>$item_name,
                    'expensetype'=>$expense_type

                ];

            //数据存入数据库    
            $a[$k]= $expense->insertGetId($arr);
        }

        //判断上传
        if($a){

            return back()->withErrors(['messageOfStatus'=>'上传成功!']);
            

        }
            return back()->withErrors(['messageOfStatus'=>'上传失败!']);

    }




public function get_item_name_expense(){

       $uid = session('member')['uid'];
       //拿到登陆者参与了阶段的项目 
        $items_member_expense = ItemTasksModel::where('member_id_task', '=', $uid)->get();
		
		
        if(!$items_member_expense->isEmpty()){
			
            //设计师循环
            foreach ($items_member_expense as $k => $v) {
                $item_id[] = $v->item_id;

            }
            //去重

            $item_id = array_unique($item_id);
            //dd($item_id);

            //根据拿到项目名
            foreach ($item_id as $k => $v) {
                $t = ItemModel::find($v);
                //dd($t);
                $join_item_name[$v]['joinItemName'] = $t['item_name'];
            }
//dd($join_item_name);
            return $join_item_name;
        }else{
			 $join_item_name=[];
            return $join_item_name;
        }

}
//显示报销附件
public function showDownload(Request $request){





    //拿到所有报销数据
    $expense = Expense::orderBy('fid', 'desc')->paginate(3);

    $join_item_name = $this->get_item_name_expense();
       
    return view('backend.expense.index',compact('expense','join_item_name'));


    }

//ajax图片
public function ajaxPic(Request $request){

    //dd($request);
    $data_pic = Expense::find($request->id);
    //return $data_pic;
    $i = Member::find($data_pic->uid);
    if( $data_pic->did == -1 ){
        $t = '无关联项目'; 
    }else{
        $t = ItemModel::find($data_pic->did);        
    }

    $e = ExpenseType::find($data_pic->type);

    $pic = $data_pic->path;

    foreach( explode(',',trim($pic,',') ) as $k=>$v ){

        if( $data_pic->did == -1 ){
            $img[] = $i->username.'/'.$t.'/'.$e->expense_type.'/'.$v;
        }else{
            $img[] = $i->username.'/'.$t->item_name.'/'.$e->expense_type.'/'.$v;            
        }       


    }

    return $img;

}






//是否通过
    public function passornot(Request $request){ 


        $expense = Expense::where('type','=',$request->type)->where('did','=',$request->did)->first();
        $expense->status = $request->id;
        $expense->reason = $request->rea;        


        if( $expense->status==0&&$expense->save() ){
            $fid=$request->fid;
            $uid=Expense::find($fid)['uid'];
            $img= Member::find($uid)['img'];//图片url
            $salary=Expense::find($fid)['salary'];
            $message =new MessageModel();
            $message->uid=Expense::find($fid)['uid'];
            $message->created_at=time();
            $message->items_name= Expense::find($fid)['itemname'];
            $message->action="报销审核通过";
            $message->img=$img;
            $message->content=Expense::find($fid)['itemname']."报销审核通过";
            $message->save();
            return 1;
        }
        $fid=$request->fid;
        $uid=Expense::find($fid)['uid'];
        $img= Member::find($uid)['img'];//图片url
        $salary=Expense::find($fid)['salary'];
        $message =new MessageModel();
        $message->uid=Expense::find($fid)['uid'];
        $message->created_at=time();
        $message->items_name= Expense::find($fid)['itemname'];
        $message->action="报销审核不通过";
        $message->content=Expense::find($fid)['itemname']."报销审核不通过";
        $message->img=$img;
        $message->save();

        $expense->save();
        return back();

    }

//搜索
    public function search(Request $request){

        //dd($request);



            $join_item_name = $this->get_item_name_expense();

            
            $startDate = strtotime($request->startDate);
            $endDate = strtotime($request->endDate);
            $content = $request->keyWords;


            if($content){
                $expense = Searchy::driver('simple')->expenses('description','username','itemname','expensetype')->query($content)->get();
            }else{
                $expense = DB::table('expenses')
                    ->whereBetween('time', [$startDate,$endDate])->get();                
            }


            return view('backend.expense.search',compact('expense','join_item_name')); 

        
    }

//打包下载
    public function accessory(Request $request){

        $task=new ItemTasksAccessoryModel();
        $taskInfo=$task->taskInfo($request->item_id,$request->task_id,$request->tag);
        $taskInfo['path'] = $task->get_path($request->task_id,$request->item_id);
        return $taskInfo;
    }
//下载
    public function newDownload($stageId){

        //阶段id1881

        //根据任意id拿到项目名
        $item_id = ItemTasksModel::find($stageId)->item_id;
        $item_name = ItemModel::find($item_id)['item_name'];
        //拿到点击的阶段名称
        $task_name = ItemTasksModel::find($stageId)['task_name'];
        //dd($task_name);
        $task_name = iconv('utf-8','gbk',$task_name);

        //保存路径
        $url = public_path()."/uploads/$item_name/$task_name/$task_name.zip";

        //下载打包的文件
        $type = 'application/zip';
        $img = "$task_name.zip";

        header("Content-type: $type"); //设置要下载的文件类型
        header("Content-Disposition: attachment; filename=$img"); //设置要下载文件的文件名
        @readfile($url);
        exit;

    }

}

